package com.appspot.gaeforum309.web;

import java.util.List;

import com.appspot.gaeforum309.core.ForumAPI;
import com.appspot.gaeforum309.db.DBCategory;
import com.appspot.gaeforum309.db.DBComment;
import com.appspot.gaeforum309.db.DBConversation;
import com.appspot.gaeforum309.db.DBTopic;
import com.appspot.gaeforum309.db.DBUser;
import com.appspot.gaeforum309.pathing.Action;
import com.appspot.gaeforum309.pathing.Path;
import com.google.appengine.labs.repackaged.com.google.common.collect.Lists;
import com.appspot.gaeforum309.pathing.PathBuilder.IPathable;
import com.appspot.gaeforum309.web.ForumPages.Page;
import com.appspot.gaeforum309.web.ForumPages.PageInfo;

public class TemplatePunBB extends Template {
	
	public static void writeActionAsForm(Action action, StringBuilder response)
	{
		response.append("<div><form action='/forumAction' method='POST'>");
		for(Action.Field field: action.getFieldsList())
		{
			switch(field.type)
			{
			case hidden:
				response.append("<p><input type='hidden' name='"+ field.name +"' value='"+ field.defaultValue +"'/></p>");
				break;
			case integer:
				response.append("<p><input type='text' name='"+ field.name +"' value='"+ field.defaultValue +"'/></p>");
				break;
			case longtext:
				response.append("<p><textarea cols=\"155\" rows=\"10\" name='"+ field.name +"'>"+ field.defaultValue +"</textarea></p>");
				break;
			case text:
				response.append("<p><input type='text' name='"+ field.name +"' value='"+ field.defaultValue +"'/></p>");
				break;
			default:
				break;
			}
		}
		response.append("<p><input type='submit' /></p></form></div>");
	}

	@Override
	public void initTemplate(PageInfo pageInfo) {
		addSection(DBCategory.tagName, new Template.ITemplateSection() {

			@Override
			public void head(StringBuilder response, Path path, IPathable object) {
				DBCategory category = (DBCategory)object;
				
				response.append("<div id=\"forum71\" class=\"main-head\"><h2 class=\"hn\"><span><a href='"+ Page.getUrl(category) +"'>"+ category.getTitre() +"</a></span></h2></div>");
				response.append("<div class=\"main-subhead\">" +
						"<p class=\"item-summary\"><span><strong class=\"subject-title\">Forum</strong> in this category with details of <strong class=\"info-topics\">Conversation</strong>, <strong class=\"info-posts\">Last</strong>, <strong class=\"info-lastpost\">Date</strong></span></p>" +
						"</div>" +
						"<div id=\"category1\" class=\"main-content main-category\">");
			}

			@Override
			public void foot(StringBuilder response, Path path, IPathable object) {
				response.append("</div>");

			}

			@Override
			public void body(StringBuilder response, Path path, IPathable object) {
				// TODO Auto-generated method stub

			}
		});
		addSection(DBTopic.tagName, new Template.ITemplateSection() {

			@Override
			public void head(StringBuilder response, Path path, IPathable object) {
				DBTopic topic = (DBTopic) object;
				// Affichage des pages
				/*
				response.append("<div " +
						"id=\"brd-pagepost-top\" class=\"main-pagepost gen-content\">"+
						"<p class=\"paging\"><span class=\"pages\">Pages</span> <strong class=\"first-item\">1</strong> <a href=\"http://punbb.informer.com/forums/forum/48/news/page/2/\">2</a> <a href=\"http://punbb.informer.com/forums/forum/48/news/page/3/\">3</a> <a href=\"http://punbb.informer.com/forums/forum/48/news/page/4/\">4</a> <a href=\"http://punbb.informer.com/forums/forum/48/news/page/2/\">Next</a></p>"+
						"<p class=\"posting\">You must <a href=\"http://punbb.informer.com/forums/login/\">login</a> or <a href=\"http://punbb.informer.com/forums/register/\">register</a> to post a new topic</p>"+
						"</div>"
						);
						*/
				
				
				// TODO: Remplacer getChilds().size() par mieux
				// TODO: Paging doit influer les valeurs affichées
				response.append("<div class=\"main-head\">"+
						"<p class=\"options\"><span class=\"feed first-item\"><a class=\"feed\" href=\"/\">RSS forum feed</a></span></p>"+
						"<h2 class=\"hn\"><span><span class=\"item-info\">Topics: 1 to "+ topic.getChilds().size() +" of "+ topic.getChilds().size() +"</span></span></h2>"+
						"</div>");
				
				response.append("<div class=\"main-subhead\">" +
						"<p class=\"item-summary forum-views\"><span><strong class=\"subject-title\">Topics</strong> in this forum with details of <strong class=\"info-replies\">replies</strong>, <strong class=\"info-views\">views</strong>, <strong class=\"info-lastpost\">last post</strong>.</span></p>" +
						"</div>");
				
				response.append("<div id=\"forum48\" class=\"main-content main-forum forum-views\">");
			}

			@Override
			public void foot(StringBuilder response, Path path, IPathable object) {
				response.append("</div>");
				
				if(Action.actionAuthorized(object, Action.ActionType.createChild))
				{
					Action action = Action.buildAction(object, Action.ActionType.createChild);
					
					TemplatePunBB.writeActionAsForm(action, response);
				}
			}

			// TODO: Add a method on IPathable to count childs objects instead of getChilds().size()
			@Override
			public void body(StringBuilder response, Path path, IPathable object) {
				DBTopic topic = (DBTopic)object;
				
				response.append("<div id=\"forum48\" class=\"main-item odd main-first-item\">" +
						"<span class=\"icon \"><!-- --></span>" +
						"<div class=\"item-subject\">" +
						"<h3 class=\"hn\"><a href=\""+ ForumPages.Page.getUrl(topic) +"\"><span>"+ topic.getTitle() +"</span></a></h3>" +
						"<p>"+topic.getDescription()+"</p>" +
						"</div>" +
						"<ul class=\"item-info\">" +
						"<li class=\"info-topics\"><strong>"+ topic.getChilds().size() +"</strong> <span class=\"label\">topics</span></li>"+
						"<li class=\"info-posts\"><strong>X</strong> <span class=\"label\">posts</span></li>" +
						"<li class=\"info-lastpost\"><span class=\"label\">Last post:</span> <strong><a href=\"http://punbb.informer.com/forums/post/145563/#p145563\">2012-06-28 07:06</a></strong> <cite>by CReatiVe4w3</cite></li>" +
						"</ul>" +
						"</div>");
			}
		});
		addSection(DBConversation.tagName, new Template.ITemplateSection() {

			@Override
			public void head(StringBuilder response, Path path, IPathable object) {
				DBConversation conversation = (DBConversation) object;
				
				// TODO: Ajouter paging
				response.append("<div id=\"brd-pagepost-top\" class=\"main-pagepost gen-content\">"+
						"<p class=\"paging\"><span class=\"pages\">Pages</span> <strong class=\"first-item\">1</strong></p>"+
						"<p class=\"posting\">You must <a href=\"http://punbb.informer.com/forums/login/\">login</a> or <a href=\"http://punbb.informer.com/forums/register/\">register</a> to post a reply</p>"+
						"</div>");
				
				response.append("<div class=\"main-head\">"+
						"<p class=\"options\"><span class=\"feed first-item\"><a class=\"feed\" href=\"/\">RSS topic feed</a></span></p>"+
						"<h2 class=\"hn\"><span><span class=\"item-info\">Posts: "+ conversation.getChilds().size() +"</span></span></h2>"+
						"</div>");
				
				response.append("<div id=\"forum68\" class=\"main-content main-topic\">");
				
			}

			@Override
			public void foot(StringBuilder response, Path path, IPathable object) {
				response.append("</div>");
				
				if(Action.actionAuthorized(object, Action.ActionType.createChild))
				{
					Action action = Action.buildAction(object, Action.ActionType.createChild);
					
					TemplatePunBB.writeActionAsForm(action, response);
				}
			}

			@Override
			public void body(StringBuilder response, Path path, IPathable object) {
				DBConversation conversation = (DBConversation) object;
				@SuppressWarnings("unchecked")
				List<DBComment> lcomments = (List<DBComment>) conversation.getChilds(0, 1);
				String author="";
				
				
				if(lcomments.size() > 0)
				{
					DBComment c = lcomments.get(0);
					DBUser a = c.getAuthor();
					author=a.getEmail();
				}
				
				// TODO: Counter of view in DBConversation
				// TODO: Search last post
				// TODO: Replace all id by real GAEForum id, or remove it !
				// TODO: Add the "em closed" only if topic is closed
				// TODO: Add a possibility to close a topic
				response.append("<div id=\"topic24927\" class=\"main-item odd main-first-item sticky closed\">"+
						"<span class=\"icon sticky closed\"><!-- --></span>"+
						"<div class=\"item-subject\">"+
						"<h3 class=\"hn\"><span class=\"item-num\">1</span> <span class=\"item-status\"><em class=\"closed\">Closed</em>:</span> <a href=\""+ Page.getUrl(conversation) +"\">"+ conversation.getTitle() +"</a></h3>"+
						"<p><span class=\"item-starter\">by <cite>"+ author  +"</cite></span> <span class=\"item-nav\">( <span>Pages&nbsp;</span><a class=\"first-item\" href=\""+ Page.getUrl(conversation) +"\">1</a>&nbsp;<a href=\""+ Page.getUrl(conversation) +"\">2</a> )</span></p>"+
						"</div>" +
						"<ul class=\"item-info\">" +
						"<li class=\"info-replies\"><strong>"+ conversation.getChilds().size() +"</strong> <span class=\"label\">replies</span></li>"+
						"<li class=\"info-views\"><strong>X</strong> <span class=\"label\">views</span></li>"+
						"<li class=\"info-lastpost\"><span class=\"label\">Last post</span> <strong><a href=\"/\">X</a></strong> <cite>by X</cite></li>"+
						"</ul>"+
						"</div>");
			}
		});
		addSection(DBComment.tagName, new Template.ITemplateSection() {

			@Override
			public void head(StringBuilder response, Path path, IPathable object) {
				
			}

			@Override
			public void foot(StringBuilder response, Path path, IPathable object) {

			}

			@Override
			public void body(StringBuilder response, Path path, IPathable object) {
				DBComment comment = (DBComment) object;
				DBUser author = comment.getAuthor();
				DBConversation conversation = (DBConversation) path.getObjectByTagName(DBConversation.tagName);
				
				// TODO: ajouter firstpost, lastpost, ou rien, pour la class du premier div
				// TODO: Add a class of user (Admin, and personalized class ?)
				// TODO: User can be online or not.
				// TODO: Determiner le nombre de posts d'un author
				// TODO: Ajouter une methode de formatage des messages(directement HTML ? ATTENTION au risque d'injection de JavaScript)
				// TODO: Add a signature on comments, and on profile.
				response.append("<div class=\"post odd topicpost\">"+
						"<div id=\"p146029\" class=\"posthead\">"+
						"<h3 class=\"hn post-ident\"><span class=\"post-num\">1</span> <span class=\"post-byline\"><span>Topic by </span><em class=\"group_color_7\"><a title=\"Go to "+ author.getEmail() +"'s profile\" href=\"/\">"+ author.getEmail() +"</a></em></span> <span class=\"post-link\"><a class=\"permalink\" rel=\"bookmark\" title=\"Permanent link to this post\" href=\""+ Page.getUrl(comment) +"\">"+ comment.getDateDiscription().toLocaleString() +"</a></span></h3>"+
						"</div>"+
						"<div class=\"postbody\">"+
						"<div class=\"post-author\">"+
						"<ul class=\"author-ident\">"+
						"<li class=\"username\"><a title=\"Go to "+ author.getEmail() +"'s profile\" href=\"/\">"+ author.getEmail() +"</a></li>"+
						"<li class=\"usertitle\"><span>Standard user</span></li>"+
						"<li class=\"userstatus\"><span>Offline</span></li>"+
						"</ul>"+
						"<ul class=\"author-info\">"+
						"<li><span>Registered: <strong>"+ author.getDateInscription() +"</strong></span></li>"+
						"<li><span>Posts: <strong>X</strong></span></li>"+
						"</ul>"+
						"</div>"+
						"<div class=\"post-entry\">"+
						"<h4 id=\"pc146029\" class=\"entry-title hn\">"+ conversation.getTitle()  +"</h4>"+
						"<div class=\"entry-content\">"+
						"<p>"+ comment.getTextComment() +"</p>"+
						"<div class=\"sig-content\"><span class=\"sig-line\"><!-- --></span>Not implemented yes</div>"+
						"</div>"+
						"</div>"+
						"</div>"+
						"</div>");
			}
		});

	}

	@Override
	public String contentType() {
		return "Text/html";
	}

	@Override
	public void beginPage(StringBuilder response, Path path) {
		response.append("<html><head><meta charset=\"utf-8\" />");
		response.append("<title>"+ ForumAPI.Config.getForumName() +"</title>");
		response.append("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/themes/PunBB/Oxygen.min.css\" />");
		response.append("<style>.group_color_1 a:link, .group_color_1 { color: #DD4B39 !important; }\n" +
				".group_color_1 a:visited { color: #DD4B39; }\n" +
				".group_color_1 a:hover { color: #C12E1C; }\n" +
				".group_color_1 { color: #C12E1C; }\n" +
				"\n" +
				".group_color_4 a:link, .group_color_4 { color: #800000 !important; }\n" +
				".group_color_4 a:visited { color: #800000; }\n" +
				".group_color_4 a:hover { color: #FF6666; }\n" +
				".group_color_4 { color: #FF6666; }\n" +
				"\n" +
				".group_color_7 a:link, .group_color_7 { color: #B42000 !important; }\n" +
				".group_color_7 a:visited { color: #B42000; }\n" +
				".group_color_7 a:hover { color: #005900; }\n" +
				".group_color_7 { color: #005900; }\n" +
				"\n" +
				".group_color_8 a:link, .group_color_8 { color: #006633 !important; }\n" +
				".group_color_8 a:visited { color: #006633; }\n" +
				".group_color_8 a:hover { color: #000033; }\n" +
				".group_color_8 { color: #000033; }\n" +
				"\n" +
				".group_color_10 a:link, .group_color_10 { color: #4B088A !important; }\n" +
				".group_color_10 a:visited { color: #4B088A; }\n" +
				".group_color_10 a:hover { color: #307D7E; }\n" +
				".group_color_10 { color: #307D7E; }\n" +
				"\n" +
				".group_color_12 a:link, .group_color_12 { color: #c0c0c0 !important; }\n" +
				".group_color_12 a:visited { color: #c0c0c0; }\n" +
				".group_color_12 a:hover { color: #ff0000; }\n" +
				".group_color_12 { color: #ff0000; }</style>\n" +
				"<style>#topcontrol{font-size:.8em;padding:.4em .5em .5em;border-radius:.3em;color:#cb4b16;font-weight:bold;cursor:pointer;z-index:10;background:#e6eaf6;background:-moz-linear-gradient(center top,#f5f7fd,#e6eaf6) repeat scroll 0 0 transparent;background:-o-linear-gradient(top,#f5f7fd,#e6eaf6);background:-webkit-gradient(linear,0 0,0 100%,from(#f5f7fd),to(#e6eaf6));background:-webkit-linear-gradient(top,#f5f7fd,#e6eaf6);background:-ms-linear-gradient(top,#f5f7fd,#e6eaf6);background:linear-gradient(top,#f5f7fd,#e6eaf6);text-shadow:0 1px 1px #bbb;-moz-box-shadow:0 1px 2px rgba(0,0,0,.2);-webkit-box-shadow:0 1px 2px rgba(0,0,0,.2);box-shadow:0 1px 2px rgba(0,0,0,.2)}#topcontrol:hover{color:#db4c18;-moz-transform:scaley(1.15);-webkit-transform:scaley(1.15)}</style>\n");

		response.append("</head><body>");
		response.append("<div class=\"hr\"><hr /></div><div id=\"brd-main\">");
		// TODO: Add a description field on the config
		response.append("<div id=\"brd-wrap\" class=\"brd\">" +
				"<div id=\"brd-index\" class=\"brd-page basic-page\">" +
				"<div id=\"brd-head\" class=\"gen-content\">" +
				"<p id=\"brd-access\"><a href=\"#brd-main\">Skip to forum content</a></p>" +
				"<p id=\"brd-title\"><a href=\"/\">"+ForumAPI.Config.getForumName()+"</a></p>" +
				"<p id=\"brd-desc\">This template is a port of the default PunBB template. Thank to the PunBB project.</p>" +
				"</div>");
		response.append("<h1 class=\"main-title\">"+ ForumAPI.Config.getForumName() +"</h1>");
		
		response.append("<div id=\"brd-visit\" class=\"gen-content\"><p id=\"welcome\">");
		if(!ForumAPI.loggedUser())
		{
			response.append("<span>You are not logged in.</span> <span>Please <a href='"+ ForumAPI.userLoginLogoutUrl(Page.getUrl(path.object())) +"'>login</a> with your Google Account.</span></p>");
			//response.append("<p id=\"visit-links\" class=\"options\"><span id=\"visit-recent\" class=\"first-item\"><a href=\"http://punbb.informer.com/forums/search/recent/\" title=\"Find topics which contain recent posts.\">Active topics</a></span> <span id=\"visit-unanswered\"><a href=\"http://punbb.informer.com/forums/search/unanswered/\" title=\"Find topics which have not been replied to.\">Unanswered topics</a></span>");
		}
		else
		{
			DBUser user = ForumAPI.userLogin();
			
			response.append("<p><span>Welcome "+ user.getEmail() +". </span>");
			if(user.isFirstLogin())
			{
				// TODO: Add an API to get first login form URI.
				response.append("<span>This is your first login, please fill our <a href='/firstLogin'>first login form</a>. </span>");
			}
			
			response.append("<span>You can <a href='"+ ForumAPI.userLoginLogoutUrl(Page.getUrl(path.object())) +"'>logout</a></span></p>");
		}
		response.append("</p></div>");
		
		response.append("<div id=\"brd-crumbs-top\" class=\"crumbs\"><p>");
	
		boolean isFirst = true;
		for(IPathable ip: Lists.reverse(path.getPath()))
		{
			boolean isLast = (path.object() == ip);
			
			response.append("<span class=\"crumb"+ (isLast?" crumblast":"") + (isFirst?" crumbfirst":"") +"\">"+ (!isFirst?"<span> -> </span>":"") + "<a href=\""+ Page.getUrl(ip) +"\">"+ ip.label() +"</a></span>");
			isFirst = false;
		}
		
		response.append("</div>");
	}

	@Override
	public void endPage(StringBuilder response, Path path) {
		response.append("</div></body></html>");
		
	}
}
